module delay_pulse_generator 
#
(
    parameter DELAY_CYCLES = 'd39,
    parameter DELAY_WIDTH = 7
)
(
    input  wire      sys_clk,   // 100MHz clock
    input  wire      low_clk,   // 20MHz clock
    input  wire      sys_rst_n, // System reset (active low)
    input  wire      done,      // Trigger signal (sys_clk domain)
    output reg       pulse_out  // Output pulse (sys_clk domain)
);

// 在sys_clk域展宽done信号，确保能被low_clk可靠采样
reg done_extended;
reg done_dly;
wire done_rise = done & ~done_dly;  // 检测done上升沿

// 将展宽后的done信号同步到low_clk域
reg [1:0] done_sync_low;
always @(posedge low_clk or negedge sys_rst_n) begin
    if (!sys_rst_n)
        done_sync_low <= 2'b00;
    else
        done_sync_low <= {done_sync_low[0], done_extended};
end

// 在low_clk域生成清除信号（确认捕获）
reg done_sync_clear;
always @(posedge low_clk or negedge sys_rst_n) begin
    if (!sys_rst_n) begin
        done_sync_clear <= 1'b0;
    end else begin
        done_sync_clear <= done_sync_low[1];
    end
end

always @(posedge sys_clk or negedge sys_rst_n) begin
    if (!sys_rst_n) begin
        done_dly <= 1'b0;
        done_extended <= 1'b0;
    end else begin
        done_dly <= done;
        
        // 检测到上升沿时展宽信号
        if (done_rise) 
            done_extended <= 1'b1;
        // 在low_clk域确认捕获后清除展宽信号
        else if (done_sync_clear)
            done_extended <= 1'b0;
    end
end

// 在low_clk域检测同步后的上升沿
reg done_sync_low_dly;
always @(posedge low_clk or negedge sys_rst_n) begin
    if (!sys_rst_n)
        done_sync_low_dly <= 1'b0;
    else
        done_sync_low_dly <= done_sync_low[1];
end

wire done_low_rise = done_sync_low[1] & ~done_sync_low_dly;

// 计数器实现200个low_clk周期延时
reg [DELAY_WIDTH:0] counter;
reg counter_en;
wire counter_done = (counter == DELAY_CYCLES);  //计数

always @(posedge low_clk or negedge sys_rst_n) begin
    if (!sys_rst_n) begin
        counter_en <= 1'b0;
        counter <= 8'd0;
    end else begin
        // 检测到同步后的上升沿时启动计数器
        if (done_low_rise)
            counter_en <= 1'b1;
        // 计数完成后停止计数器
        else if (counter_done)
            counter_en <= 1'b0;
        
        // 计数器逻辑
        if (!counter_en)
            counter <= 8'd0;
        else if (!counter_done)
            counter <= counter + 1'b1;
    end
end

// 在low_clk域生成完成信号
reg done_low;
always @(posedge low_clk or negedge sys_rst_n) begin
    if (!sys_rst_n)
        done_low <= 1'b0;
    else
        done_low <= counter_done;
end

// 将完成信号同步回sys_clk域
reg [2:0] done_sync_sys;
always @(posedge sys_clk or negedge sys_rst_n) begin
    if (!sys_rst_n)
        done_sync_sys <= 3'b000;
    else
        done_sync_sys <= {done_sync_sys[1:0], done_low};
end

// 在sys_clk域检测上升沿生成输出脉冲
always @(posedge sys_clk or negedge sys_rst_n) begin
    if (!sys_rst_n)
        pulse_out <= 1'b0;
    else
        pulse_out <= done_sync_sys[1] & ~done_sync_sys[2];
end

endmodule